package com.richie696.rabbit.order.controller;

import com.richie696.rabbit.commons.ExecuteResult;
import com.richie696.rabbit.commons.RabbitKey;
import com.richie696.rabbit.order.domain.OrderInfo;
import com.richie696.rabbit.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@Component
@RequestMapping("/order")
public class OrderController {

    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @RequestMapping("/list/{userId}")
    public String getOrderList(@PathVariable Long userId, Model model) {
        List<OrderInfo> orders = orderService.findOrdersByUserId(userId);
        model.addAttribute("orders", orders);
        return "/client/order_list";
    }

    @PostMapping("/payment")
    public String orderPage(@RequestParam("uid") Long userId, @RequestParam("pid") Long productId,
            @RequestParam("num") Integer num, Model model) {
        ExecuteResult<?> orderExec = orderService.doBuy(userId, productId, num);
        if (!orderExec.isSuccess()) {
            model.addAttribute("errorMsg", orderExec.getErrorMessage());
            model.addAttribute("pid", productId);
            return "/client/error";
        }
        model.addAttribute("order", orderExec.getData());
        model.addAttribute("timer", RabbitKey.EXPIRATION / 1000);
        return "/client/payment";
    }

    @PostMapping("/payment_exec")
    public String doPayment(@RequestParam("oid") String orderId, @RequestParam("uid") Long userId, Model model) {
        ExecuteResult<Long> result = orderService.doPayment(userId, orderId);
        if (result.isSuccess()) {
            return "/client/result";
        }
        model.addAttribute("errorMsg", result.getErrorMessage());
        model.addAttribute("pid", result.getData());
        return "/client/error";
    }
}
